package com.nondo.rdp.auth.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.nondo.rdp.core.json.JsonObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.condition.SearchStrategy;
import org.springframework.boot.autoconfigure.web.*;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.Servlet;
import java.util.List;

/**
 * rdp-project
 *
 * @author linfeng@nondo
 * @since 2017/9/22.
 */
@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass({Servlet.class, DispatcherServlet.class})
@AutoConfigureBefore(WebMvcAutoConfiguration.class)
@EnableConfigurationProperties({ServerProperties.class, ResourceProperties.class})
public class WebMvcConfig {

    private final List<ErrorViewResolver> errorViewResolvers;
    private final ServerProperties serverProperties;

    @Autowired(required = false)
    public WebMvcConfig(
            ServerProperties serverProperties, List<ErrorViewResolver> errorViewResolvers) {
        this.serverProperties = serverProperties;
        this.errorViewResolvers = errorViewResolvers;
    }

    @Bean
    @ConditionalOnMissingBean(value = GlobalErrorController.class, search = SearchStrategy.CURRENT)
    public BasicErrorController basicErrorController(ErrorAttributes errorAttributes) {

        return new BasicErrorController(errorAttributes, serverProperties.getError(), this.errorViewResolvers);
    }

    @Bean
    @ConditionalOnMissingBean(value = GlobalErrorAttributes.class, search = SearchStrategy.CURRENT)
    public DefaultErrorAttributes errorAttributes() {
        return new DefaultErrorAttributes();
    }

    @Bean
    public ObjectMapper objectMapper() {
        return new JsonObjectMapper();
    }

}
